package in.co.codedoc.cg.velocity;

import in.co.codedoc.cg.BeanUtil;
import in.co.codedoc.cg.TypeUtil;

import java.io.StringWriter;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

public class VelocityAdapter
{
	private static String[] userdirectives = 
	{
		"in.co.codedoc.cg.velocity.ForEachClassDirective",
		"in.co.codedoc.cg.velocity.ForEachMethodDirective",
		"in.co.codedoc.cg.velocity.ForEachPackageDirective",
		"in.co.codedoc.cg.velocity.IfNthRoundDirective",
		"in.co.codedoc.cg.velocity.CreateJavaFileDirective",
		"in.co.codedoc.cg.velocity.PropertyAccessBlockDirective",
		"in.co.codedoc.cg.velocity.ClassAccessBlockDirective",
		"in.co.codedoc.cg.velocity.CreateTextFileDirective",
		"in.co.codedoc.cg.velocity.MethodParameterAccessBlockDirective"
	};
	
	public VelocityAdapter(String templatesDir,String moduleLogCategory,String ... templateNames)
	{
		this.templatesDir = templatesDir;
		this.moduleLogCategory = moduleLogCategory;
		this.templateNames = templateNames;
	}

	private String templatesDir;
	private String moduleLogCategory;
	private String[] templateNames;
	
	public void execute()
	{
		for (String templateName : templateNames)
		{
			try
			{
				for (String userdirective : userdirectives)
				{
					Velocity.addProperty
					(
						"userdirective",
						userdirective
					);
				}
				
				Velocity.addProperty
				(
					"file.resource.loader.path",
					templatesDir
				);
				
				Velocity.init();
				VelocityContext context = new VelocityContext();

				context.put("moduleLogCategory",moduleLogCategory);
				context.put("BeanUtil",new BeanUtil());
				context.put("TypeUtil",new TypeUtil());
				
				try
				{
					Template template = Velocity.getTemplate(templateName);
					
					StringWriter output = new StringWriter();
					template.merge(context, output);	
					output.flush();
				}
				finally
				{
					context.remove("moduleLogCategory");
					context.remove("BeanUtil");
					context.remove("TypeUtil");
				}
				//System.out.print(output.toString());
			}
			catch(Throwable th)
			{
				throw new RuntimeException(th);
			}
		}
	}
}
